"""
Author： Mr.Sun
Datetime： 2023/3/27 11:10 
FileName: send_request.py
Desc: 
"""

import json
import urllib3
import requests
from requests.adapters import HTTPAdapter
from utils.logger import logger

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
requests.packages.urllib3.disable_warnings()


class SendRequest(object):
    def __init__(self, url, params=None, method='data', headers=None):
        self.url = url
        self.method = str(method).lower()
        self.params = params
        self.headers = headers
        self.session = requests.Session()
        self.session.mount('http://', HTTPAdapter(max_retries=3))
        self.session.mount('https://', HTTPAdapter(max_retries=3))

    def GetRequest(self):
        log_dict = {
            "url": self.url,
            "request_type": "GET",
            "request_params": self.params,
            "request_header": self.headers
        }
        logger.info("SendRequest.GetRequest information " + json.dumps(log_dict, ensure_ascii=False))
        response = self.session.get(self.url, headers=self.headers, params=self.params, verify=False)
        try:
            result = json.dumps(response, ensure_ascii=False)
            return result
        except Exception as e:
            result = response.text
            logger.error("SendRequest.GetRequest error :" + str(e))
            return result

    def PostRequest(self):
        log_dict = {
            "url": self.url,
            "request_type": "POST",
            "request_params": self.params,
            "request_header": self.headers
        }
        if self.method == "data":
            log_dict['method'] = 'data'
            logger.info("SendRequest.PostRequest information is " + json.dumps(log_dict, ensure_ascii=False))
            response = self.session.post(self.url, headers=self.headers, data=self.params, verify=False)
        # json 处理方式，或者使用data=json.dumps(data)，将字典转成json
        else:
            log_dict['method'] = 'json'
            logger.info("SendRequest.PostRequest information is " + json.dumps(log_dict, ensure_ascii=False))
            response = self.session.post(self.url, headers=self.headers, json=self.params, verify=False)
        try:  # indent=2,
            result = json.dumps(response.json(), ensure_ascii=False)
            return result
        except Exception as e:
            logger.error("SendRequest.PostRequest error :" + str(e))
            result = response.text
            return result
